package com.yikome.utils;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.yikome.constant.CommonConstant;

import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.text.csv.CsvWriter;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;

public class AsyncCsvUtils {

	public static String handleCsvDatas(List<Map<String, Object>> datas , String subName) {
		
		if(!datas.isEmpty()) {
			
			String filePath = CommonConstant.BASE_LOCATION + LocalDateTime.now(ZoneId.of("+8")).format(CommonConstant.DATETIMEFORMATTRT_DATE) + '/' + LocalDateTime.now(ZoneId.of("+8")).format(CommonConstant.DATETIMEFORMATTRT_TIME) + "-" + subName + ".csv" ; 
			
			CsvWriter writer = CsvUtil.getWriter(filePath, CharsetUtil.CHARSET_UTF_8);
			
			Set<String> keySet = new LinkedHashSet<>(datas.get(0).keySet());
			writer.write(keySet.toArray(new String[] {}));
			for (Map<String, Object> map : datas) {
				
				writer.write(getMapValuesArray(keySet, map));
			}
			writer.close();
			return filePath ;
		}
		return "" ;
	}
	
	private static String[] getMapValuesArray(Set<String> keySet , Map<String, Object> map) {
		
		List<String> lists = new ArrayList<>();
		
		for (String key : keySet) {
			lists.add(StrUtil.toString(map.get(key)));
		}
		
		return ArrayUtil.toArray(lists, String.class);
	}
}
